import React from 'react';
import { DatePicker, List } from 'antd-mobile';
import { PropsType } from 'antd-mobile/lib/date-picker';
import dayjs from 'dayjs';
import classnames from 'classnames';
import { transformDate } from './utils';
import './index.less';


interface DatePickerProps extends Omit<PropsType, 'value' | 'format'> {
  title?: string;
  id?: string;
  required?: boolean;
  value?: string | number;
  format?: string;
}
type State = {};

const Index: React.FC<DatePickerProps> = ({
  children,
  title,
  required,
  id,
  value,
  onChange,
  format,
  disabled,
  ...props
}) => {
  let newValue = value as any;
  if (value) {
    try {
      newValue = transformDate(value);
    } catch (error) {
      console.log(`${title}, ${error}`);
      newValue = undefined;
    }
  }
  const handleChange = (date) => {
    if (typeof onChange === 'function') {
      onChange(date.getTime());
      // onChange(formatText(date));
    }
  };
  const formatText = (date) => {
    if (format) {
      return dayjs(date).format(format);
    }
    return dayjs(date).format('YYYY-MM-DD');
  };
  return (
    <div className={classnames('hr-datepicker', { disabled, placeholder: !newValue })} id={id}>
      <DatePicker
        {...props}
        disabled={disabled}
        format={formatText}
        onChange={handleChange}
        value={newValue as Date}
      >
        <List.Item arrow="horizontal">
          {required && <span className="require-icon">*</span>}
          {title}
        </List.Item>
      </DatePicker>
    </div>
  );
};
Index.defaultProps = {};

export default Index;
export { transformDate };
